<!--
 * @Author: zhudx
 * @Date: 2023-09-18 10:55:27
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2025-04-09 11:27:44
 * @FilePath: /vue3-admin/src/components/ui/Image/HeicImage.vue
 * @Description: heic图片回显
-->

<script setup lang="ts">
import heic2any from 'heic2any';
import { ref, onMounted, watch, onBeforeUnmount } from 'vue';
import { Picture as IconPicture } from '@element-plus/icons-vue';
import { getImageById } from '@/utils/index';

const props = withDefaults(
    defineProps<{
        id: number; // 图片id
        src: string; // 图片类型
        path?: string; // 文件地址
    }>(),
    {
        src: ''
    }
);

const imageSrc = ref([] as string[]);
const imageSrcBlob = ref('');

const getBase64 = (imgUrl: any) => {
    let base64 = '';
    window.URL = window.URL || window.webkitURL;
    var xhr = new XMLHttpRequest();
    xhr.open('get', imgUrl, true);
    // 至关重要
    xhr.responseType = 'blob';
    xhr.onload = function () {
        if (this.status == 200) {
            var blob = this.response;
            // console.log("blob", blob)
            // 至关重要
            let oFileReader = new FileReader();
            oFileReader.onloadend = function (e) {
                base64 = e.target?.result as string;
                // console.log("方式一》》》》》》》》》", oFileReader);
                heic2jpt(base64);
            };
            oFileReader.readAsDataURL(blob);
        }
    };
    xhr.send();
};

const heic2jpt = (base64: any) => {
    return new Promise((resolve, reject) => {
        let data = atob(base64.split(',')[1]);
        let n = data.length;
        let u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = data.charCodeAt(n);
        }
        let blob = new Blob([u8arr]);
        // console.log('blob',data.length,blob)
        heic2any({
            blob,
            toType: 'image/png',
            quality: 1
        })
            .then((conversionResult) => {
                // conversionResult is a BLOB
                resolve(blobToFile(conversionResult));
            })
            .catch((e) => {
                console.error('error', e);
            });
    });
};

const blobToFile = (blob: any) => {
    const imgSrc = URL.createObjectURL(new Blob([blob]));
    imageSrcBlob.value = imgSrc;
    imageSrc.value.push(imgSrc);
};

const getUrl = () => {
    if (
        props.path?.split('.')[1] === 'heic' ||
        props.path?.split('.')[1] === 'HEIC'
    ) {
        getBase64(getImageById(props.id));
    } else {
        imageSrcBlob.value = getImageById(props.id);
        imageSrc.value.push(getImageById(props.id));
    }
};

onMounted(() => {
    // console.log('-------', props.path?.split('.')[1])
    // if(props.path?.split('.')[1] === 'heic' || props.path?.split('.')[1] === 'HEIC' ) {
    //     getBase64(props.src);
    // }else {
    //     imageSrcBlob.value = props.src;
    //     imageSrc.value.push(props.src)
    // }
    getUrl();
});

const watchFn = watch(
    () => props.id,
    (newVal) => {
        if (props.id) {
            imageSrcBlob.value = '';
            imageSrc.value = [];
            getUrl();
        }
    }
);
onBeforeUnmount(() => {
    imageSrcBlob.value = '';
    imageSrc.value = [];
    watchFn();
});
</script>

<template>
    <div class="filesupload-container">
        <!-- {{ props.id }} -->
        <el-image
            :src="imageSrcBlob"
            style="width: 50px; height: 50px; border: 1px solid #eee"
            class="mr10"
            :preview-src-list="imageSrc"
        >
            <template #error>
                <div class="image-slot">
                    <el-icon><icon-picture /></el-icon>
                </div>
            </template>
        </el-image>
    </div>
</template>
